<template>
  <view class="rocker-qrcode-app">
    <view class="scan-container" @click="scanItem" v-if="state==0">
      <view class="image">
        <image src="../../../static/scan.png" style="width:400upx;height:400upx;"></image>
      </view>
      <view class="btn btn-primary btn-scan">点击扫描售货柜上的二维码</view>
    </view>
    <view class="rent" v-if="state==1">
      <view class="head" style="border-bottom: 1upx solid #eee;">商品列表</view>
      <view class="items">
        <view class="item" v-for="(item,key) in listData.items" :key="key" v-if="item.goods&&item.goods.goodsName">
          <view class="item-container">
            <view class="img">
              <image v-if="!item.goods.goodsPic" src="../../../static/good_0.png"
                     style="width:150upx;height:150upx;"></image>
              <image v-if="item.goods.goodsPic"
                     :src="item.goods.goodsPic"
                     mode="aspectFit" style="width: 150upx;height:150upx;"></image>
            </view>
            <view class="info">
              <view class="name">{{ item.goods.goodsName }}</view>
              <view class="desc">{{ item.goods.goodsDesc }}</view>
              <view class="price">
                <text class="stock" style="display: inline-block;width:150upx;">库存：{{ item.currSize }}</text>
                <text class="money">售价：
                  <text style="color:red">{{ item.goods.outPrice }}</text>
                  元
                </text>
              </view>
            </view>
          </view>
          <view class="btn btn-primary" @click="buy(item)">立即购买</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>

import util from '@/libs/util.js'
import globalConfig from "@/config";
const baseHttp = globalConfig.API_HOST

export default {
  data() {
    return {
      baseHttp: baseHttp,
      isLogin: false,
      machineNO: "",
      state: 0,
      wxCode: "",
      isBuySubmit: false,
      listData: {
        items: []
      }
    }
  },
  onLoad(params) {
    // params.scene = '864917055336895'
    if (params.scene) {
      this.machineNO = params.scene;
      //this.state = 1;
      //this.getGoodsList();

      if (global.isLogin()) {
        this.isLogin = true
        //登录了，直接显示扫码的内容
        if (this.machineNO) {

        } else {
          try {
            let machineNO = uni.getStorageSync('good_machineNO');
            if (machineNO) {
              this.machineNO = machineNO;
              uni.removeStorageSync('good_machineNO');
            }
          } catch (e) {
            //TODO handle the exception
          }
        }

        if (this.machineNO) {
          this.state = 1;
          this.getGoodsList();
        }

      } else {
        this.isLogin = false
        //跳转到登录界面
        if (this.machineNO) {
          try {
            uni.setStorageSync('good_machineNO', this.machineNO);
          } catch (e) {
            //TODO handle the exception
          }
        }
        this.goPage('/pages/user/auth/auth');
      }

    }
  },
  onShow() {

    try {
      let machineNO = uni.getStorageSync('good_machineNO');
      if (machineNO) {
        this.machineNO = machineNO;
        uni.removeStorageSync('good_machineNO');
      }
    } catch (e) {
      //TODO handle the exception
    }

    if (this.machineNO) {
      this.state = 1;
      this.getGoodsList();
    }

  },
  components: {},
  computed: {},
  methods: {
    ...util,
    buy(item) {
      wx.login({
        success: (res) => {
          if (res.code) {
            console.log(1000)
            this.wxCode = res.code;
            this.$api.post('/goodsChannel/buy',
                {
                  goodsChannelId: item.goodsChannelId,
                  code: this.wxCode
                }
            ).then((response) => {
              console.log(response)
              if (response.data) {
                this.toPay(response.data, item);
              } else {
                if (response.ret === 1) {
                  this.$Message.success("购买成功");
                } else {
                  if (response.msg == "余额不足") {
                    this.$Message.error(response.msg);
                    this.goPage("/pages/user/info/vip?teaHouseId=" + this.listData.items[0].teaHouseId);
                  } else {
                    this.$Message.error(response.msg)
                  }
                }
              }
            });
          }
        }
      });
    },
    toPay(responseData, item) {

      //console.log(response);
      let json = "{" + responseData + "}";
      json = json.replace(/'/g, '"');
      json = JSON.parse(json);

      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: json.timeStamp,
        nonceStr: json.nonceStr,
        package: json.package,
        signType: json.signType,
        paySign: json.paySign,
        success: (res) => {
          //this.buy(item);
          this.$Message.success("支付成功");
          /*
          uni.navigateBack({
            delta: 1
          });
          */
        },
        fail: function (err) {
          console.log('fail:' + JSON.stringify(err));
        }
      });

    },
    bindPickerChange: function (field, arrName, e) {
      let selectItem = this[arrName][e.target.value]
      this.item[field] = selectItem.name
    },
    scanItem() {
      uni.scanCode({
        success: (res) => {
          if (res.result) {
            res.result = res.result.replace(/^\s+|\s+$/g, "");
            this.machineNO = res.result;
            this.state = 1;
            this.getGoodsList();
          } else {
            this.$Message.error("识别失败");
          }

        }
      });
    },
    getGoodsList() {
      this.$api.post('/goodsChannel/getChannelAndGoods',
          {
            machineNO: this.machineNO,
          }
      ).then((response) => {
        if (response.ret === 1) {
          this.listData.items = response.data;
          for (let i = 0; i < this.listData.items.length; i++) {
            if (this.listData.items[i].goods) {
              this.listData.items[i].goods.outPrice = this.listData.items[i].goods.outPrice / 100;
            }
          }
        } else {
          this.$Message.error(response.msg)
        }
      })
    }
  }
}
</script>

<style lang="scss">
page {
  height: 100%;
}

.rocker-qrcode-app {

  .scan-container {

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    text-align: center;
    margin-top: 100 upx;

    .image {
    }

    .text {
    }

    .btn-scan {
      padding: 20 upx;
      width: 600 upx;
      margin-top: 50 upx;
    }
  }

  .rent {
    .head {
      /*border-bottom:1upx solid #eee;*/
      text-align: center;
      font-weight: bold;
      padding: 10 upx;
    }

    .btn-pay {
      padding: 20 upx;
      width: 650 upx;
      margin-top: 20 upx;
      margin-left: 20 upx;
    }

    .item-container {
      display: flex;
    }

    .items {
      .item {
        padding: 20 upx;
        margin: 20 upx;
        border: 1 upx solid #eee;

        .img {
          width: 150 upx;
          height: 150 upx;
          border: 1 upx solid #eee;
          border-radius: 10 upx;
          overflow: hidden;
          /*background-color: #eee;*/
        }

        .info {
          flex: 1;
          margin-left: 20 upx;

          .name {
            font-size: 32 upx;

          }

          .desc {
            font-size: 28 upx;
            color: #ccc;
            margin: 10 upx 0;
          }

          .price {
          }

        }

        .btn {
          margin: 0 auto;
          margin-top: 20 upx;
        }
      }
    }
  }
}
</style>
